import React, { useRef } from 'react'
import { Modal, Form, InputNumber, Input } from 'antd'
import PropTypes from 'prop-types'
import style from './ModifyFee.module.less'
import { strToNum } from '@src/assets/js/tool'

const { TextArea } = Input
const { Item } = Form

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
}

function Fee ({ value }) {
  return (
    <span>{`¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}</span>
  )
}

// 改变值
function changeValue (ref, key, v) {
  const current = ref.current
  current.setFieldsValue({
    [key]: v
  })
  computeAndSetFee(ref)
}

// 计算费用
function computeAndSetFee (ref) {
  const current = ref.current
  const feeAcceptance = current.getFieldValue('fee_acceptance') || 0
  const feeProcessing = current.getFieldValue('fee_processing') || 0
  current.setFieldsValue({
    fee: strToNum(feeAcceptance) + strToNum(feeProcessing)
  })
}

function Main ({ visible, initData, onChange, hide }) {
  const ref = useRef(null)
  return (
    <Modal
      title='修改仲裁费'
      open={visible}
      destroyOnClose
      onOk={() => ref.current.submit()}
      onCancel={() => hide()}
    >
      <Form name={`modify_fee_${Date.now()}`} {...layout} initialValues={initData} ref={ref} onFinish={(v) => onChange(v)}>
        <Item label='新受理费' name='fee_acceptance' rules={[{ required: true, message: '受理费不能为空' }]}>
          <InputNumber
            className={style.input}
            formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/¥\s?|(,*)/g, '')}
            onChange={v => changeValue(ref, 'fee_acceptance', v)}
          />
        </Item>
        <Item label='新处理费' name='fee_processing' rules={[{ required: true, message: '处理费不能为空' }]}>
          <InputNumber
            className={style.input}
            formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/¥\s?|(,*)/g, '')}
            onChange={v => changeValue(ref, 'fee_processing', v)}
          />
        </Item>
        <Item label='新仲裁费' name='fee'>
          <Fee />
        </Item>
        <Item label='原因' name='log' rules={[{ required: true, message: '原因不能为空' }]}>
          <TextArea rows={3} />
        </Item>
      </Form>
    </Modal>
  )
}

Main.propTypes = {
  initData: PropTypes.object,
  hide: PropTypes.func,
  visible: PropTypes.bool,
  onChange: PropTypes.func
}

Main.defaultProps = {
  initData: {},
  hide: () => {},
  visible: false,
  onChange: () => {}
}

export default Main
